<?php

namespace App\Containers\AppSection\Moneybox\Actions;

use App\Containers\AppSection\File\Models\File;
use App\Containers\AppSection\File\Tasks\FindFileByIdTask;
use App\Containers\AppSection\Profile\Models\Profile;
use App\Ship\Exceptions\BadRequestException;
use App\Ship\Exceptions\NotFoundException;
use App\Ship\Parents\Actions\SubAction;
use Carbon\Carbon;
use Exception;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Support\Facades\File as FileSystem;
use Illuminate\Support\Facades\Storage;

class ClientDataSubAction extends SubAction
{
    /**
     * @throws NotFoundException
     * @throws FileNotFoundException
     * @throws BadRequestException
     * @throws Exception
     */
    public function run(array &$client, string $uuid, Profile $profile, string $method, $isBeneficiary = true)
    {
        $client['virtual_account'] = strval($profile->id);

        switch ($profile->legal_form_type) {
            case 'entity':
                $client['type_legal'] = 'J';
                break;
            case 'indiv':
                $client['type_legal'] = 'F';
                break;
            case 'ie':
                $client['type_legal'] = 'I';
                break;
        }

        // Компания
        if ($profile->hasLegalForm('entity')) {
            $client['kpp'] = $profile->legal_form->company->inn;
            $client['organization_name'] = $profile->legal_form->company->name;
            $client['organization_address'] = $profile->legal_form->company->legal_address;
        } else if ($profile->hasLegalForm('ie')) {
            $client['organization_name'] = 'ИП ' . $profile->legal_form->personal->fio;
            $client['organization_address'] = $profile->legal_form->personal->residence_address;
        }

        $client['inn'] = $profile->legal_form->personal->inn;

        //ФИО
        $client['name'] = $profile->legal_form->personal->fio;
        $name_ar = preg_split('/ /', $client['name'], 3);
        if (!$name_ar || count($name_ar) < 2) {
            throw new Exception("ФИО неверное");
        }
        $client['last_name'] = trim($name_ar[0]);
        $client['first_name'] = trim($name_ar[1]);
        if (count($name_ar) > 2) $client['middle_name'] = trim($name_ar[2]);

        $client['registration_address'] = $profile->legal_form->personal->registration_address;
        $client['passport_num'] = $profile->legal_form->passport->serial_number;
        $client['passport_date'] = (new Carbon($profile->legal_form->passport->issue_date))->format('Y-m-d');
        $client['subdivision_code'] = $profile->legal_form->passport->department_code;
        $client['subdivision_name'] = $profile->legal_form->passport->issued_by;
        $client['birth_date'] = (new Carbon($profile->legal_form->personal->birth_date))->format('Y-m-d');
        $client['birth_place'] = $profile->legal_form->personal->birth_place;


        if ($isBeneficiary) {
            $client['documents'] = [];
            if ($profile->hasLegalForm('entity')) {
                // TODO доработать оферту
                $ofertaFile = app(FindFileByIdTask::class)->run(101453);
                $oferta = $this->getBeneficiaryDoc($uuid, $ofertaFile, 5, $method);
                $client['documents'][] = $oferta;
            } else {
                $first_photo = $this->getBeneficiaryDoc($uuid, $profile->legal_form->passport->first_photo, 6, $method);
                $client['documents'][] = $first_photo;

                $second_photo = $this->getBeneficiaryDoc($uuid, $profile->legal_form->passport->second_photo, 7, $method);
                $client['documents'][] = $second_photo;
            }
        }
    }

    /**
     * @throws BadRequestException|FileNotFoundException
     */
    private function getBeneficiaryDoc(string $uuid, File $file, int $type, string $method): array
    {
        /*$url = app(GetUrlFileTask::class)->run($file->id);
        if (empty($url)) {
            throw new BadRequestException();
        }*/
        $contents = Storage::disk(config('filesystems.cloud'))->get($file->path);

        FileSystem::makeDirectory(public_path('/storage/' . $method . '/' . $uuid), 0777, true, true);

        $doc = Storage::disk('public')->put('/' . $method . '/' . $uuid . '/' . basename($file->path), $contents, 0777);
        if ($doc !== true) {
            throw new BadRequestException();
        }

        $path = Storage::disk('public')->url($file->path);

        return [
            'number' => strval($file->id),
            'file' => $path,
            'type' => $type,
            'date' => (new Carbon($file->created_at))->format('Y-m-d')
        ];
    }
}
